﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RCREEE.Library;
using RCREEE.Library.Entities;
//using AjaxControlToolkit.HTMLEditor;
using AjaxControlToolkit;
using RCREEE.Web.Classes;
using BulletedList = System.Web.UI.WebControls.BulletedList;

namespace RCREEE.Web
{
    public partial class ItemsList : System.Web.UI.Page
    {
        #region Properties
        private string QS_MultiValueItems = "MultiValueItems";
        private string QS_SelectedMultiValueItem = "SelectedMultiValueItem";
        private string QS_AllLanguages = "AllLanguages";

        private string SS_LangCode = "LanguageCode";
        private string VS_PageTitle = "PageTitle";

        public int EntityId
        {
            get
            {
                int entityid = 0;
                if (Request.QueryString[QueryStrings.QS_EntityId] != null)
                    int.TryParse(Request.QueryString[QueryStrings.QS_EntityId], out entityid);
                return entityid;
            }
        }
        public int LanguageCode
        {
            get
            {
                int langCode = 1033;
                if (Session[SS_LangCode] != null)
                    int.TryParse(Session[SS_LangCode].ToString(), out langCode);
                return langCode;
            }
            set
            {
                Session[SS_LangCode] = value;
            }
        }
        //public int SelectedLanguageId
        //{
        //    get
        //    {
        //        int langId;
        //        int.TryParse(ddlLanguages.SelectedValue, out langId);
        //        return langId;
        //    }
        //}

        public string PageTitle
        {
            get
            {
                if (ViewState[VS_PageTitle] != null)
                    return ViewState[VS_PageTitle].ToString();
                return string.Empty;
            }
            set
            {
                ViewState[VS_PageTitle] = value;
            }
        }
        public List<MultiValueItem> MultiValueItems
        {
            get
            {
                if (Session[QS_MultiValueItems] != null)
                    return (List<MultiValueItem>)Session[QS_MultiValueItems];

                return new List<MultiValueItem>();
            }
            set
            {
                Session[QS_MultiValueItems] = value;

            }
        }

        public MultiValueItem SelectedMultiValueItem
        {
            get
            {
                if (Session[QS_SelectedMultiValueItem] != null)
                    return (MultiValueItem)Session[QS_SelectedMultiValueItem];

                return new MultiValueItem();
            }
            set
            {
                Session[QS_SelectedMultiValueItem] = value;

            }
        }

        public List<KeyValuePair<int, string>> LanguageList
        {
            get
            {
                if (Session[QS_AllLanguages] != null)
                    return (List<KeyValuePair<int, string>>)Session[QS_AllLanguages];

                return new List<KeyValuePair<int, string>>();
            }
            set
            {
                Session[QS_AllLanguages] = value;

            }
        }

        //public User User
        //{
        //    get
        //    {
        //        if (Session[SS_User] != null)
        //            return (User)Session[SS_User];

        //        return new User();
        //    }
        //    set
        //    {
        //        Session[SS_User] = value;

        //    }
        //}

        public User User
        {
            get
            {
                return ((RCREEE.Web.Site)Page.Master).User;

                // return new User();
            }
            set
            {
                ((RCREEE.Web.Site)Page.Master).User = value;

            }
        }

        public int CountryId
        {
            get
            {
                int countryId;
                int.TryParse(ddlCountries.SelectedValue, out countryId);
                return countryId;
            }
        }


        public bool CanAdd
        {
            get
            {
                if (User != null)
                {
                    return User.UserPermissions.Any(perm => perm.CountryId == CountryId && perm.CanAdd);
                }
                return false;
            }
        }


        public bool CanUpdate
        {
            get
            {
                if (User != null)
                {
                    return User.UserPermissions.Any(perm => perm.CountryId == CountryId && perm.CanUpdate);
                }
                return false;
            }
        }


        public bool CanDelete
        {
            get
            {
                if (User != null)
                {
                    return User.UserPermissions.Any(perm => perm.CountryId == CountryId && perm.CanDelete);
                }
                return false;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //var con = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                //LanguageCode = (int)LanguagesEnum.English;

                //User = DataManager.GetUserData(1, LanguageCode);

                var allCountries = DataManager.GetCountries(LanguageCode);
                var emptyCountry = allCountries.FirstOrDefault(country => country.ID == 0);
                if (emptyCountry != null)
                {
                    emptyCountry.Name = "All";
                }
                ddlCountries.DataSource = allCountries;
                ddlCountries.DataBind();

                //ddlCountries.Items.Insert(0, new ListItem("All", "0"));

                //ddlLanguages.DataSource = Enum.GetNames(typeof(LanguagesEnum));
                //ddlLanguages.DataBind();                

                LanguageList = new List<KeyValuePair<int, string>>();

                LanguageList.Add(new KeyValuePair<int, string>((int)LanguagesEnum.English, LanguagesEnum.English.ToString()));
                LanguageList.Add(new KeyValuePair<int, string>((int)LanguagesEnum.Arabic, LanguagesEnum.Arabic.ToString()));
                LanguageList.Add(new KeyValuePair<int, string>((int)LanguagesEnum.French, LanguagesEnum.French.ToString()));
                //ddlLanguages.DataSource = list;
                //ddlLanguages.DataBind();

                //ddlLanguages.SelectedValue = LanguageCode.ToString();

                GetAllItems();
                HandleCountryFromQueryString();
            }
            Page.Title = PageTitle;
        }

        private void HandleCountryFromQueryString()
        {
            int countryId = 0;
            if (Request.QueryString[QueryStrings.QS_CountryId] != null)
            {
                int.TryParse(Request.QueryString[QueryStrings.QS_CountryId], out countryId);
                if (countryId > 0 && ddlCountries.Items.FindByValue(countryId.ToString()) != null)
                {
                    ddlCountries.SelectedValue = countryId.ToString();
                    MultiView.ActiveViewIndex = 1;
                    BindCountryData(countryId);
                    HandlePermission();
                }
            }
        }

        protected override void InitializeCulture()
        {
            if (LanguageCode > 0)
            {
                string languageId = "en-US";
                if (LanguageCode == (int)LanguagesEnum.French)
                    languageId = "fr-FR";
                if (LanguageCode == (int)LanguagesEnum.Arabic)
                    languageId = "ar-EG";
                if (LanguageCode == (int)LanguagesEnum.English)
                    languageId = "en-US";
                Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(languageId);

                Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageId);
            }

            base.InitializeCulture();
        }

        private void GetAllItems()
        {
            if (EntityId > 0)
            {
                RefreshAllMultivalueItems();

                //rpt.DataSource = ds.MultiValueItems;
                //rpt.DataBind();

                grdAllCountriesItems.DataSource = MultiValueItems;
                grdAllCountriesItems.DataBind();

                fvCadres.DataSource = null;
                fvCadres.DataBind();
            }
            else
            {
                //lblErrors.Text = ("Some data are missing.");
                Response.Redirect(string.Format("Error.aspx?{0}={1}", QueryStrings.QS_Error, "Category must be specified."));
            }
        }

        private void RefreshAllMultivalueItems()
        {
            int countryId;
            int.TryParse(ddlCountries.SelectedValue, out countryId);
            var ds = DataManager.GetItemCountryMasterValues(countryId, EntityId, LanguageCode);

            Page.Title = PageTitle = lblItemName.Text = ds.Item.Name;
            MultiValueItems = ds.MultiValueItems;
        }


        protected void Rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item != null && (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem))
            {
                var multiValueItemData = (MultiValueItem)e.Item.DataItem;
                var lblCounry = e.Item.FindControl("lblCounry") as Label;
                var rptMultiValueItems = e.Item.FindControl("rptMultiValueItems") as Repeater;
                // var datalistMultiValueItems = e.Item.FindControl("datalistMultiValueItems") as DataList;



                lblCounry.Text = multiValueItemData.Country.CountryName;

                rptMultiValueItems.DataSource = multiValueItemData.MultiValueItemDataValues;
                rptMultiValueItems.DataBind();

                // datalistMultiValueItems.DataSource = multiValueItemData.MultiValueItemDataValues;
                // datalistMultiValueItems.DataBind();
            }
        }

        protected void GrdCountryItems_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null && (e.Row.RowType == DataControlRowType.DataRow))
            {

                var multiValueItemData = (MultiValueItem)e.Row.DataItem;
                var lblCountryName = e.Row.FindControl("lblCountryName") as Label;
                var imgCountryFlag = e.Row.FindControl("imgCountryFlag") as Image;
                //var rptMultiValueItems = e.Row.FindControl("rptMultiValueItems") as Repeater;
                var bulletedlistMultiValueItems = e.Row.FindControl("bulletedlistMultiValueItems") as BulletedList;

                lblCountryName.Text = multiValueItemData.Country.CountryName;
                imgCountryFlag.ImageUrl = "Images/Flags/" + multiValueItemData.Country.FlagImagePath;

                //rptMultiValueItems.DataSource = multiValueItemData.MultiValueItemDataValues;
                // rptMultiValueItems.DataBind();

                bulletedlistMultiValueItems.DataSource = multiValueItemData.MultiValueItemDataValues;
                bulletedlistMultiValueItems.DataBind();
            }
        }

        protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            int countryId;
            int.TryParse(ddlCountries.SelectedValue, out countryId);
            if (countryId > 0)
            {
                MultiView.ActiveViewIndex = 1;
                BindCountryData(countryId);
                HandlePermission();
            }
            else
            {
                MultiView.ActiveViewIndex = 0;
                GetAllItems();
            }
        }

        private void HandlePermission()
        {

            btnAddCadre.Visible = btnAddItemValue.Visible = CanAdd;

        }


        protected void GrdAllCountriesItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedValue = (int)grdAllCountriesItems.SelectedValue;
            SelectedMultiValueItem = MultiValueItems.FirstOrDefault(item => item.MultiValueItemId == selectedValue);
            if (SelectedMultiValueItem != null)
            {
                fvCadres.DataSource = SelectedMultiValueItem.Cadres;
                fvCadres.DataBind();
            }
        }

        //protected void FrmViewCadres_PageIndexChanged(object sender, EventArgs e)
        //{
        //    throw new NotImplementedException();
        //}


        #region CountryView

        protected void FrmViewCadres_PageIndexChanging(object sender, FormViewPageEventArgs e)
        {
            fvCadres.PageIndex = e.NewPageIndex;
            int selectedCadreId = (int)fvCadres.SelectedValue;
            var selectedItem = MultiValueItems.FirstOrDefault(item => item.Cadres.Any(cad => cad.CadreId == selectedCadreId));
            if (selectedItem != null)
            {
                fvCadres.DataSource = selectedItem.Cadres;
                fvCadres.DataBind();
            }
        }

        protected void BtnAddCadre_Clicked(object sender, EventArgs e)
        {
            fvCadres.ChangeMode(FormViewMode.Insert);
            if (SelectedMultiValueItem != null)
            {
                fvCadres.DataSource = SelectedMultiValueItem.Cadres;
                fvCadres.DataBind();
            }
        }

        protected void BtnSave_Clicked(object sender, EventArgs e)
        {
            if (SelectedMultiValueItem != null)
            {
                var insertTemplate = ((Button)sender).Parent.Parent;
                if (insertTemplate != null)
                {
                    var editorCadre = (TextBox)insertTemplate.FindControl("editorCadre");
                    DropDownList ddlLanguages = (DropDownList)insertTemplate.FindControl("ddlLanguages");
                    int multiValueItemId = SelectedMultiValueItem.MultiValueItemId;

                    int langCode = LanguageCode;
                    int.TryParse(ddlLanguages.SelectedValue, out langCode);
                    int countryId;
                    int.TryParse(ddlCountries.SelectedValue, out countryId);
                    if (multiValueItemId == 0)
                    {
                        multiValueItemId = DataManager.InsertMultiValueItem(countryId, EntityId);
                        SelectedMultiValueItem.MultiValueItemId = multiValueItemId;
                        SelectedMultiValueItem.Country = new Country { CountryId = countryId };
                    }
                    DataManager.InsertMultiItemValueCadre(multiValueItemId, langCode, editorCadre.Text);
                    fvCadres.ChangeMode(FormViewMode.ReadOnly);
                    RefreshAllMultivalueItems();
                    RefreshCadres();
                }
            }
        }

        protected void BtnEdit_Clicked(object sender, EventArgs e)
        {
            fvCadres.ChangeMode(FormViewMode.Edit);
            if (SelectedMultiValueItem != null)
            {
                fvCadres.DataSource = SelectedMultiValueItem.Cadres;
                fvCadres.DataBind();
            }
        }


        protected void BtnCancelCadre_Clicked(object sender, EventArgs e)
        {
            fvCadres.ChangeMode(FormViewMode.ReadOnly);
            RefreshCadres();
        }

        protected void BtnSaveChange_Clicked(object sender, EventArgs e)
        {
            if (SelectedMultiValueItem != null)
            {
                var editTemplate = ((Button)sender).Parent.Parent;
                int cadreId;
                if (editTemplate != null && int.TryParse(fvCadres.SelectedValue.ToString(), out cadreId) && cadreId > 0)
                {
                    var txtEditCadre = (TextBox)editTemplate.FindControl("txtEditCadre");
                    var editorCadreEdit = (TextBox)editTemplate.FindControl("editorCadreEdit");
                    DataManager.EditMultiItemValuCadre(cadreId, editorCadreEdit.Text);
                    fvCadres.ChangeMode(FormViewMode.ReadOnly);
                    RefreshAllMultivalueItems();
                    RefreshCadres();
                }
            }
        }

        private void RefreshCadres()
        {
            int countryId;
            int.TryParse(ddlCountries.SelectedValue, out countryId);
            SelectedMultiValueItem = MultiValueItems.FirstOrDefault(item => item.Country.CountryId == countryId);
            if (SelectedMultiValueItem != null)
            {
                fvCadres.DataSource = SelectedMultiValueItem.Cadres;
                fvCadres.DataBind();
            }
        }

        private void BindCountryData(int countryId)
        {
            SelectedMultiValueItem = MultiValueItems.FirstOrDefault(item => item.Country.CountryId == countryId);
            if (SelectedMultiValueItem != null)
            {
                lvMultiViewItemValues.DataSource = SelectedMultiValueItem.MultiValueItemDataValues;
                //Commented for Demo Purpose
                //gridCountryItems.DataSource = SelectedMultiValueItem.MultiValueItemDataValues;
                lvMultiViewItemValues.DataBind();
                fvItems.DataSource = null;
                fvItems.DataBind();
                fvCadres.DataSource = SelectedMultiValueItem.Cadres;
                fvCadres.DataBind();
            }
        }

        protected void GrdCountryItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectedMultiValueItem != null)
            {
                int selectedValue = (int)gridCountryItems.SelectedValue;
                var multiValueItemDataValue = SelectedMultiValueItem.MultiValueItemDataValues.FirstOrDefault(item => item.MultiValueItemDataValueId == selectedValue);
                if (multiValueItemDataValue != null)
                {
                    fvItems.DataSource = new List<MultiValueItemDataValue> { multiValueItemDataValue };
                    fvItems.DataBind();
                }
            }
        }



        protected void BtnAddItemValue_Clicked(object sender, EventArgs e)
        {
            fvItems.ChangeMode(FormViewMode.Insert);
        }


        protected void BtnEditItem_Clicked(object sender, EventArgs e)
        {
            fvItems.ChangeMode(FormViewMode.Edit);
            int selectedValue = (int)gridCountryItems.SelectedValue;
            var multiValueItemDataValue = SelectedMultiValueItem.MultiValueItemDataValues.FirstOrDefault(item => item.MultiValueItemDataValueId == selectedValue);
            if (multiValueItemDataValue != null)
            {
                fvItems.DataSource = new List<MultiValueItemDataValue> { multiValueItemDataValue };
                fvItems.DataBind();
            }
        }

        protected void BtnSaveItem_Clicked(object sender, EventArgs e)
        {
            if (SelectedMultiValueItem != null)
            {
                var insertTemplate = ((Button)sender).Parent.Parent;
                if (insertTemplate != null)
                {
                    var txtItem = (TextBox)insertTemplate.FindControl("txtItem");
                    DropDownList ddlLanguages = (DropDownList)insertTemplate.FindControl("ddlLanguages");
                    int multiValueItemId = SelectedMultiValueItem.MultiValueItemId;

                    int langCode = LanguageCode;
                    int.TryParse(ddlLanguages.SelectedValue, out langCode);
                    int countryId;
                    int.TryParse(ddlCountries.SelectedValue, out countryId);
                    if (multiValueItemId == 0)
                    {
                        multiValueItemId = DataManager.InsertMultiValueItem(countryId, EntityId);
                        SelectedMultiValueItem.MultiValueItemId = multiValueItemId;
                        SelectedMultiValueItem.Country = new Country { CountryId = countryId };
                    }
                    DataManager.InsertMultiItemValueValue(multiValueItemId, langCode, txtItem.Text);
                    fvItems.ChangeMode(FormViewMode.ReadOnly);
                    RefreshAllMultivalueItems();
                    RefreshItems();
                    ClearSelectedItemData();
                }
            }
        }


        protected void BtnCancel_Clicked(object sender, EventArgs e)
        {
            fvItems.ChangeMode(FormViewMode.ReadOnly);
            ClearSelectedItemData();
        }

        private void ClearSelectedItemData()
        {
            fvItems.DataSource = null;
            fvItems.DataBind();
        }


        protected void BtnSaveItemChange_Clicked(object sender, EventArgs e)
        {

            if (SelectedMultiValueItem != null)
            {
                var editTemplate = ((Button)sender).Parent.Parent;
                int valueId;
                if (editTemplate != null && int.TryParse(fvItems.SelectedValue.ToString(), out valueId) && valueId > 0)
                {
                    var txtEditItem = (TextBox)editTemplate.FindControl("txtEditItem");
                    DataManager.EditMultiItemValuValue(valueId, txtEditItem.Text);
                    fvItems.ChangeMode(FormViewMode.ReadOnly);
                    RefreshAllMultivalueItems();
                    RefreshItems();

                    ClearSelectedItemData();
                }
            }
        }


        private void RefreshItems()
        {
            int countryId;
            int.TryParse(ddlCountries.SelectedValue, out countryId);
            SelectedMultiValueItem = MultiValueItems.FirstOrDefault(item => item.Country.CountryId == countryId);
            if (SelectedMultiValueItem != null)
            {
                lvMultiViewItemValues.DataSource = SelectedMultiValueItem.MultiValueItemDataValues;
                // Commented for Demo Purpose
                //gridCountryItems.DataSource = SelectedMultiValueItem.MultiValueItemDataValues;
                lvMultiViewItemValues.DataBind();
                if (gridCountryItems.SelectedValue != null)
                {
                    int selectedValue = (int)gridCountryItems.SelectedValue;
                    var multiValueItemDataValue = SelectedMultiValueItem.MultiValueItemDataValues.FirstOrDefault(item => item.MultiValueItemDataValueId == selectedValue);
                    if (multiValueItemDataValue != null)
                    {
                        fvItems.DataSource = new List<MultiValueItemDataValue> { multiValueItemDataValue };
                        fvItems.DataBind();

                    }
                }
            }
        }

        #endregion

        protected void LnkDelete_Clicked(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void GridCountryItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int valueId;
            if (gridCountryItems.DataKeys != null && gridCountryItems.DataKeys.Count > e.RowIndex)
                if (int.TryParse(gridCountryItems.DataKeys[e.RowIndex].Value.ToString(), out valueId) && valueId > 0)
                {
                    DataManager.DeleteMultiItemValuValue(valueId);
                    RefreshAllMultivalueItems();
                    RefreshItems();

                    ClearSelectedItemData();
                }
        }

        protected void BtnDeleteCadre_Clicked(object sender, EventArgs e)
        {
            if (SelectedMultiValueItem != null)
            {
                var viewTemplate = ((Button)sender).Parent.Parent;
                int cadreId;
                if (viewTemplate != null && int.TryParse(fvCadres.SelectedValue.ToString(), out cadreId) && cadreId > 0)
                {
                    DataManager.DeleteMultiItemValuCadre(cadreId);
                    RefreshAllMultivalueItems();
                    RefreshCadres();
                }
            }
        }

        protected void DdlLanguages_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllItems();

            int countryId;
            int.TryParse(ddlCountries.SelectedValue, out countryId);
            if (countryId > 0)
            {
                BindCountryData(countryId);
            }
        }

        protected void GridCountryItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null && (e.Row.RowType == DataControlRowType.DataRow))
            {
                //var lnkDelete = e.Row.FindControl("lnkDelete") as LinkButton;
                var btnDel = e.Row.FindControl("btnDel") as Button;

                //lnkDelete.Visible = CanDelete;
                btnDel.Visible = CanDelete;

                if (gridCountryItems.Columns.Count > 2)
                    gridCountryItems.Columns[2].Visible = CanDelete;
            }
        }

        protected string GetPageDirection()
        {
            try
            {

                if (Session["LanguageCode"] != null)
                    if (Session["LanguageCode"].ToString() == "1025")
                        return "rtl";
            }
            catch { return "ltr"; }

            return "ltr";
        }

        protected void fvItems_OnDataBound(object sender, EventArgs e)
        {
            if (fvItems.Row != null)
            {
                var btnEdit = fvItems.Row.FindControl("btnEdit") as Button;
                if (btnEdit != null) btnEdit.Visible = CanUpdate;
                if (fvItems.CurrentMode == FormViewMode.Insert)
                {
                    DropDownList ddlLanguages = (DropDownList)fvItems.FindControl("ddlLanguages");
                    ddlLanguages.DataSource = LanguageList;
                    ddlLanguages.DataBind();
                    ddlLanguages.SelectedValue = LanguageCode.ToString();
                }

            }
        }

        protected void fvCadres_OnDataBound(object sender, EventArgs e)
        {
            if (fvCadres.Row != null)
            {
                var btnEdit = fvCadres.Row.FindControl("btnEdit") as Button;
                var btnDeleteCadre = fvCadres.Row.FindControl("btnDeleteCadre") as Button;
                if (btnEdit != null) btnEdit.Visible = CanUpdate;
                if (btnDeleteCadre != null) btnDeleteCadre.Visible = CanDelete;
                if (fvCadres.CurrentMode == FormViewMode.Insert)
                {
                    DropDownList ddlLanguages = (DropDownList)fvCadres.FindControl("ddlLanguages");
                    ddlLanguages.DataSource = LanguageList;
                    ddlLanguages.DataBind();
                    ddlLanguages.SelectedValue = LanguageCode.ToString();
                }
            }
        }

    }
}